package com.ruoyi.function.utility;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import com.ruoyi.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl {
    
    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
    
    @Autowired
    private SmsConfig smsConfig;
    
    @Autowired
    private RedisCache redisCache;

    private static final String REGION_ID = "ap-southeast-1";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";
    private static final String CODE_KEY_PREFIX = "sms:code:";
    private static final String LIMIT_KEY_PREFIX = "sms:limit:";
    private static final int CODE_EXPIRE_MINUTES = 5;
    private static final int LIMIT_EXPIRE_MINUTES = 1;
    
    public boolean sendVerifyCode(String mobile, Integer businessType) {
        try {
            // 检查是否在限制期内
             String limitKey = LIMIT_KEY_PREFIX + mobile;
             Boolean isLimited = redisCache.getCacheObject(limitKey);
             if (isLimited != null && isLimited) {
                 log.warn("手机号{}在限制时间内重复发送验证码", mobile);
                 return false;
             }
            
            // 生成验证码
            String code = String.format("%06d", (int)(Math.random() * 1000000));
            System.out.println("发送验证码："+code);
            // 配置客户端
            Config config = new Config()
                .setAccessKeyId(smsConfig.getAccessKeyId())
                .setAccessKeySecret(smsConfig.getAccessKeySecret())
                .setEndpoint(ENDPOINT);
            
            Client client = new Client(config);
            
            // 组装请求
            SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(smsConfig.getTemplateCode())
                .setTemplateParam("{\"code\":\"" + code + "\"}");
            
            // 发送短信
            SendSmsResponse response = client.sendSms(request);
            
            // if (response != null && "OK".equals(response.getBody().getCode())) {
                if (true) {
                // 保存验证码，5分钟有效
                String codeKey = CODE_KEY_PREFIX + businessType + ":" + mobile;
                redisCache.setCacheObject(codeKey, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
                
                // 设置发送限制，1分钟内不能重复发送

                    redisCache.setCacheObject(limitKey, true, LIMIT_EXPIRE_MINUTES, TimeUnit.MINUTES);

                    return true;
            }
            return false;
        } catch (Exception e) {
            log.error("短信发送异常", e);
            log.error("AccessKeyId: {}, SignName: {}, TemplateCode: {}", 
                smsConfig.getAccessKeyId(),
                smsConfig.getSignName(),
                smsConfig.getTemplateCode());
            return false;
        }
    }
    
    public boolean verifyCode(String mobile, String code, Integer businessType) {
        String key = CODE_KEY_PREFIX + businessType + ":" + mobile;
        String cachedCode = redisCache.getCacheObject(key);
        if (cachedCode != null && cachedCode.equals(code)) {
            redisCache.deleteObject(key);
            return true;
        }
        return false;
    }

    /**
     * 发送短信
     * @param mobile 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendSms(String mobile, String code) {
        try {
            // 配置客户端
            Config config = new Config()
                .setAccessKeyId(smsConfig.getAccessKeyId())
                .setAccessKeySecret(smsConfig.getAccessKeySecret())
                .setEndpoint(ENDPOINT);
            
            Client client = new Client(config);
            
            // 组装请求
            SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(smsConfig.getTemplateCode())
                .setTemplateParam("{\"code\":\"" + code + "\"}");
            
            // 发送短信
            SendSmsResponse response = client.sendSms(request);
            
            return response != null && "OK".equals(response.getBody().getCode());
        } catch (Exception e) {
            log.error("短信发送异常", e);
            return false;
        }
    }
} 